

/**
 * ...
 * @author Thot
 */

function EditorModel(){}

EditorModel._instance = null;
EditorModel.getInstance = function()
{
	if( EditorModel._instance == null )
		EditorModel._instance = new EditorModel();
		
	return EditorModel._instance;
};

EditorModel.prototype.autoSave = true;
EditorModel.prototype.autoSaveTime = 10000;
EditorModel.prototype.portraitWidth = 100;
EditorModel.prototype.portraitHeight = 80;
EditorModel.prototype.portraitId = 1000;
EditorModel.prototype.landscapeId = 2000;
EditorModel.prototype.ficheId = -1;
EditorModel.prototype.saveURLFiche = "";
EditorModel.prototype.saveURLImage = "";
EditorModel.prototype.assetsPath = "";
EditorModel.prototype.uiPath = "";

EditorModel.prototype._uiTextures = [
	{url:'picker.png',name:'picker'},
	{url:'cross.png',name:'cross'},
	{url:'resize.png',name:'resize'},
	{url:'rotation.png',name:'rotation'},
	{url:'up.png',name:'up'},
	{url:'DPE_0.png',name:'dpe'},
	{url:'GES_0.png',name:'ges'},
];

EditorModel.prototype._container = null;
EditorModel.prototype._addBackgroundButton = null;
EditorModel.prototype._addTextButton = null;
EditorModel.prototype._addImageButton = null;
EditorModel.prototype._addDPEButton = null;
EditorModel.prototype._addGESButton = null;
EditorModel.prototype._rentButton = null;
EditorModel.prototype._sellButton = null;
EditorModel.prototype._portraitButton = null;
EditorModel.prototype._landscapeButton = null;
EditorModel.prototype._titeField = null;
EditorModel.prototype._themeField = null;
EditorModel.prototype._formatField = null;
EditorModel.prototype._saveButton = null;
EditorModel.prototype._textEditor = null;
EditorModel.prototype._time = 0;
EditorModel.prototype._data = null;
EditorModel.prototype._fileReader = null;
EditorModel.prototype._textureManager = null;
EditorModel.prototype._ratio = 1;
EditorModel.prototype._numFiles = 0;
EditorModel.prototype._totalRequest = 0;

//public init
EditorModel.prototype.init = function(data)
{
	this._data = data;
	this._initCanvas();
	this._textEditor = new TextEditor();
	this._textEditor.init("texteditor");
	this._elementEditor = new ElementEditor();
	this._elementEditor.init();
	this._initListeners();
	this._initAssets();
	this.setLoaderVisible(false);
	this.changeOrientation();
};

EditorModel.prototype._appReady = function()
{
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var data = loader.getData();
	var tex = null;
	
	for( var prop in data )
	{
		tex = new tomahawk_ns.Texture();
		tex.name = prop;
		tex.data = data[prop];
		tex.rect = [0,0,data[prop].width,data[prop].height];
		
		tomahawk_ns.AssetsManager.getInstance().addTexture(tex,tex.name);
	}
		
	this._loadData(this._data);
	tomahawk_ns.Stage.getInstance().addEventListener( tomahawk_ns.Event.ENTER_FRAME, this, this._enterFrame );
};

EditorModel.prototype._progressHandler = function(event)
{
	var loader = event.target;
};

EditorModel.prototype._initAssets = function()
{
	var usedTextures = this._getUsedTextures();
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var i = usedTextures.length;
	var obj = null;
	
	loader.addEventListener( tomahawk_ns.Event.COMPLETE, this, this._appReady );
	loader.addEventListener( tomahawk_ns.Event.PROGRESS, this, this._progressHandler );
	
	while( --i > -1 )
	{
		loader.addFile(this.assetsPath + usedTextures[i], usedTextures[i]);
		this._numFiles++;
	}
	
	i = this._uiTextures.length;
	
	while( --i > -1 )
	{
		obj = this._uiTextures[i];
		loader.addFile( this.uiPath + obj.url, obj.name );
		this._numFiles++;
	}
	
	loader.load();
};

EditorModel.prototype.changeOrientation = function(event)
{
	var DOMEditor = document.getElementById("editorZone");
	var ratio = this.portraitWidth / this.portraitHeight;
	var background = this._container.getChildByName("ficheBackground");
	var canvas = document.getElementById("canvasEditor"); 
	var value = ( this._portraitButton.checked ) ? this.portraitId : this.landscapeId;
	
	if( background == null )
		background = new tomahawk_ns.Shape();
		
	//landscape
	if( value == this.portraitId )
	{
		ratio = this.portraitWidth / this.portraitHeight;
		canvas.width = AppConstants.BASE_SIZE;
		canvas.height = canvas.width / ratio;
	}
	else
	{
		canvas.height = AppConstants.BASE_SIZE;
		canvas.width = canvas.height / ratio;
	}
	
	canvas.style.marginTop = parseInt(( DOMEditor.offsetHeight - canvas.height ) * 0.5)+'px';
	canvas.style.marginLeft = parseInt(( DOMEditor.offsetWidth - canvas.width ) * 0.5)+'px';
	
	// plain background
	background.name = "ficheBackground";
	background.beginPath();
	background.fillStyle("white");
	background.fillRect(0,0,100,100);
	background.fill();
	background.width = 100;
	background.height = 100;
	background.scaleX = canvas.width / background.width;
	background.scaleY = canvas.height / background.height;
	background.cacheAsBitmap = true;
	
	//set mouseEnabled to true
	background.mouseEnabled = true;
	
	tomahawk_ns.Stage.getInstance().addChildAt(background,0);
};

EditorModel.prototype._initCanvas = function()
{
	var canvas = document.getElementById("canvasEditor"); 
	this._container = new tomahawk_ns.Sprite();
	this._container.mouseEnabled = true;
	
	// init tomahawk
	tomahawk_ns.Stage.getInstance().init(canvas);
	tomahawk_ns.Stage.getInstance().addChild(this._container);
};

EditorModel.prototype._loadData = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var child = null;
	var i = 0;
	var max = data.length;

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];
		
		if( dataChild.type == "TransformableBitmap" )
			child = new TransformableBitmap();
		
		if( dataChild.type == "MesureComponent" )
			child = new MesureComponent();
		
		if( dataChild.type == "TransformableText" )
			child = new TransformableText();
		
		if( child == null )
			continue;
			
		child.unserialize(dataChild);
		container.addChild(child);
	}
};



//private
EditorModel.prototype._getUsedTextures = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var i = 0;
	var max = data.length;
	var results = new Array();

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];

		if( dataChild.type == "TransformableBitmap" && dataChild.textureName != null)
		{
			results.push(dataChild.textureName);
		}
	}
	
	return results;
};

EditorModel.prototype._enterFrame = function(event)
{
	var curTime = new Date().getTime();
	if( curTime - this._time > this.autoSaveTime )
	{
		if( this.autoSave == true )
			this.save();
			
		this._time = curTime;
	}
	//tomahawk_ns.Stage.getInstance().drawFPS();
};

EditorModel.prototype._focusHandler = function(event)
{
	if( event.type == tomahawk_ns.Event.FOCUSED || event.type == tomahawk_ns.Event.UNFOCUSED )
	{
		var target = ( event.type == tomahawk_ns.Event.FOCUSED ) ? event.target : null;
		this._textEditor.setCurrentTextField(target);
	}
	
	if( event.type == EditorEvent.SELECT_OBJECT || event.type == EditorEvent.UNSELECT_OBJECT )
	{
		var target = ( event.type == EditorEvent.SELECT_OBJECT ) ? event.target : null;
		if( target != null )
			this._elementEditor.setCurrentElement(target);
	}
};

EditorModel.prototype._initListeners = function()
{
	var scope = this;
	var callback1 = function(){scope._mouseHandler.apply(scope,arguments);};
	var callback2 = function(){scope.save.apply(scope,arguments);};
	var callback3 = function(){scope.changeOrientation();};
	
	this._addBackgroundButton = document.getElementById('addBackgroundImage');
	this._addImageButton = document.getElementById('addImage');
	this._addDPEButton = document.getElementById('addDPE');
	this._addGESButton = document.getElementById('addGES');
	this._addTextButton = document.getElementById('addText');
	this._rentButton = document.getElementById('rentButton');
	this._sellButton = document.getElementById('sellButton');
	this._saveButton = document.getElementById('save');
	this._titeField = document.getElementById('ficheTitle');
	this._goodTypeField = document.getElementById('goodType');
	this._rentField = document.getElementById('rent');
	this._publicField = document.getElementById('public');
	this._themeField = document.getElementById('ficheTheme');
	this._formatField = document.getElementById('ficheFormat');
	this._portraitButton = document.getElementById('portraitBtn');
	this._landscapeButton = document.getElementById('landscapeBtn');
	this._addPrice = document.getElementById('addPrice');
	this._addTitle = document.getElementById('addTitle');
	this._addDetails = document.getElementById('addDetails');
	this._addHook = document.getElementById('addHook');
	
	this._container.addEventListener(tomahawk_ns.Event.FOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(tomahawk_ns.Event.UNFOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.SELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.UNSELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.USER_IMAGE_ADDED, this, this._addUserImageHandler,true);
	
	this._addHook.onclick = callback1;
	this._addDetails.onclick = callback1;
	this._addPrice.onclick = callback1;
	this._addTitle.onclick = callback1;
	this._addBackgroundButton.onclick = callback1;
	this._addTextButton.onclick = callback1;
	this._addImageButton.onclick = callback1;
	this._addDPEButton.onclick = callback1;
	this._addGESButton.onclick = callback1;
	this._rentButton.onclick = callback1;
	this._sellButton.onclick = callback1;
	this._saveButton.onclick = callback2; // save
	this._portraitButton.onclick = callback3;
	this._landscapeButton.onclick = callback3;
};

EditorModel.prototype._mouseHandler = function(event)
{
	//centre, par défaut, sélectionné
	var child = null;
	var container = EditorModel.getInstance()._container;
	var stage  = tomahawk_ns.Stage.getInstance();
	var texture = null;
	var format = new tomahawk_ns.TextFormat();
	
	if( event.target == this._addHook )
	{
		format.size = 20;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(300,150,150,50);
		child.setText(Localization.getInstance().getLabel("ACCROCHE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "hook";
	}
	
	if( event.target == this._addImageButton )
	{
		child = new TransformableBitmap();
	}
	
	if( event.target == this._addTitle )
	{
		format.size = 30;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(0,0,150,50);
		child.setText(Localization.getInstance().getLabel("TITRE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "title";
	}		
	
	if( event.target == this._addDetails )
	{
		format.size = 12;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(100,100,150,50);
		child.setText(Localization.getInstance().getLabel("DETAILS"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "details";
	}	
	
	if( event.target == this._addPrice )
	{
		format.size = 20;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(300,20,150,50);
		child.setText(Localization.getInstance().getLabel("PRIX"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "price";
	}
	
	if( event.target == this._addBackgroundButton )
	{
		child = container.getChildByName("background");
		if( child != null )
		{
			container.removeChild(child);
		}
		
		child = new TransformableBitmap();
		child.name = "background";
		child.resize(stage.getCanvas().width,stage.getCanvas().height);
	}
	
	if( event.target == this._addDPEButton )
	{
		//child = new TransformableBitmap();
		child = new MesureComponent();
		child.name = "dpe";
		texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('dpe');
		child.resize( 200, 100 );
		child.setTexture(texture);
		child.resizeByWidth();
		child.range = MesureComponent.RANGE_DPE;
	}
	
	if( event.target == this._addGESButton )
	{
		child = new MesureComponent();
		child.name = "ges";
		texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('ges');
		child.resize( 200, 100 );
		child.setTexture(texture);
		child.resizeByWidth();
		child.range = MesureComponent.RANGE_GES;
	}

	if( event.target == this._addTextButton )
	{
		child = new TransformableText();
		child.init(50,50,100,100);
		child.setText(Localization.getInstance().getLabel("VOTRE_TEXTE_ICI"));
		child.autoFocus();
		child.padding = 15;
	}	
	
	if( event.target == this._rentButton )
	{
		format.size = 30;
		format.textColor = "white";
		child = new TransformableText(format);
		child.init(200,200,150,50);
		child.setText(Localization.getInstance().getLabel("LOUE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.rotation = -45;
		child.background = true;
		child.backgroundColor = "red";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "rent";
	}	
	
	if( event.target == this._sellButton )
	{
		format.size = 30;
		format.textColor = "white";
		child = new TransformableText(format);
		child.init(200,200,150,50);
		child.setText(Localization.getInstance().getLabel("VENDU"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.rotation = -45;
		child.background = true;
		child.backgroundColor = "red";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "sell";
	}
	
	if( child != null )
	{
		if( child.name == "background" )
		{
			container.addChildAt( child, 0 );
		}
		else
		{
			container.addChild( child );
		}
	}
	
	event.target.blur();
	stage.getCanvas().focus();
};


EditorModel.prototype.setLoaderVisible = function(value)
{
	if( value == true )
	{
		document.getElementById('loaderImg').style.visibility = 'visible';
	}
	else
	{
		document.getElementById('loaderImg').style.visibility = 'hidden';
	}
};



EditorModel.prototype._addUserImageHandler = function(event)
{
	var data = event.data.data;
	var fileName = event.data.name;
	this.setLoaderVisible(true);
	this._totalRequest++;
	
	ImageFileSaver.onComplete = this._saveComplete.bind(this);
	ImageFileSaver.save(this.saveURLImage+"&ficheId="+this.ficheId,data,fileName);
};

EditorModel.prototype._saveComplete = function()
{
	this._totalRequest = ( this._totalRequest - 1 <  0 ) ? 0 : this._totalRequest - 1;
	this.setLoaderVisible(this._totalRequest > 0);
};

//save fiche data
EditorModel.prototype.save = function()
{
	var orientation = ( this._portraitButton.checked ) ? this._portraitButton.value : this._landscapeButton.value;
	var url = this.saveURLFiche+"&ficheId="+this.ficheId;
	var child = null;
	var i = 0;
	var max = this._container.children.length;
	var save = new Array();
	var stage = tomahawk_ns.Stage.getInstance();
	
	// LVM
	//var ratio = 150 / stage.getCanvas().width;
	var ratio;
	
	var preview = document.createElement("canvas");
	var context = preview.getContext("2d");
	var str = null;
	
	// LVM : pour obtenir un aperçu de meilleur qualité lorsqu'on le zoome 
	// avec le passage de souris dans les pages de pré-création fiche et modèle
	// et voir ainsi, surtout pour les modèles publics, une vision du modèle à choisir
	// beaucoup plus claire avant l'édition 
	var zoom = 6;
	
	for (i = 0; i < max; i++)
	{
		child = this._container.children[i];
		save.push(child.serialize());
	}
	
	// LVM
	//preview.width = 150;
	//preview.height = 107;
	
	if (this._portraitButton.checked)
	{
		preview.width = 150;
		preview.height = 210; 
		
		ratio = preview.width / stage.getCanvas().width;
	} 
	else 
	{ 
		preview.width = 150;
		preview.height = 107;
		
		ratio = preview.height / stage.getCanvas().height;
	}
	
	// LVM
	preview.width = zoom*preview.width;
	preview.height = zoom*preview.height;
	
	// LVM
	context.scale(ratio, ratio);
	//context.scale(1, 1);
	
	context.drawImage(stage.getCanvas(),0,0);
	
	
	str = JSON.stringify(save);
	
	url += "&ficheName="+this._titeField.value;
	url += "&ficheTheme="+this._themeField.value;
	url += "&ficheFormat="+this._formatField.value;
	url += "&goodType="+this._goodTypeField.value;
	url += "&rent="+this._rentField.value;
	url += "&public="+this._publicField.value;
	url += "&orientation="+orientation;
	
	this.setLoaderVisible(true);
	this._totalRequest++;
	
	FicheSaver.onComplete = this._saveComplete.bind(this);
	FicheSaver.save(url,str,preview.toDataURL());
};











/**
 * ...
 * @author HTML5
 */

function Arrow()
{
	tomahawk_ns.Sprite.apply(this);
	this.mouseEnabled = true;
	this._shape = this._drawShape();
	this._field = this._drawTextField();
	this.addChild(this._shape);
	this.addChild(this._field);
	this.width = 100;
	this.height= 54;
	
	this._field.name = "arrow_field";
}

Tomahawk.registerClass( Arrow, "Arrow" );
Tomahawk.extend( "Arrow", "Sprite" );

Arrow.prototype._field = null;
Arrow.prototype._shape = null;
Arrow.prototype._lastValue = 0;
Arrow._currentArrow = null;

Arrow.prototype.getValue = function()
{
	return parseInt(this._field._text);
};

Arrow.prototype.draw = function(context)
{
	var value = this.getValue();
	
	if( value != this._lastValue  && !isNaN(value) )
	{
		this._lastValue = value;
		this.dispatchEvent( new tomahawk_ns.Event("change",true,true) );
	}
	
	tomahawk_ns.Sprite.prototype.draw.apply(this,[context]);
};

Arrow.prototype.setValue = function(value)
{
	this._field.setText(value+"");
};

Arrow.prototype.select = function(value)
{
	this._field.setFocus(value);
	this._field.setCurrentIndex(0);
};

Arrow.prototype._drawTextField = function()
{
	var field = new tomahawk_ns.InputTextField();
	var format = new tomahawk_ns.TextFormat();
	format.size = 30;
	format.textColor = "black";
	
	field.cursorColor = "black";
	field.mouseEnabled = true;
	field.defaultTextFormat = format;
	field.width = 75;
	field.height = 35;
	field.y = 10;
	field.x = 20;
	field.background = true;
	field.setTextAlign( tomahawk_ns.TextField.ALIGN_CENTER);
	field.backgroundColor = "white";
	field.setText("0");
	
	return field;
};

Arrow.prototype._drawShape = function()
{
	var shape = new tomahawk_ns.Shape();
	shape.clear();
	shape.width = 85;
	shape.height = 54;
	shape.mouseEnabled = true;
	shape.beginPath();
	shape.fillStyle("black");
	shape.moveTo(0,27);
	shape.lineTo(15,0);
	shape.lineTo(15,54);
	shape.lineTo(0,27);
	shape.fill();
	shape.beginPath();
	shape.fillRect(14,0,85,54);
	shape.fill();
	
	shape.beginPath();
	shape.moveTo(0,27);
	shape.lineTo(-360, 27);
	shape.stroke();
	
	return shape;
};





/**
 * ...
 * @author Hatshepsout
 1 A4 = 5 watts
 1 A3 = 10 watts
1 alimentation au minimum dans une vitrine
calculer le nombre
pour les gammes c2.max et i.max fixation cable bas en haut
gamme one et budget entre les afficheurs -> mini cables trois : longueurs différentes + cable de fixation en haut
wall format = tout est posé sur un mur
 */
// it is a DOM element controller who can dispatchEvent according to the Tomahawk's EventDispatcher API

function ColorPicker()
{
	tomahawk_ns.EventDispatcher.apply(this);
}

Tomahawk.registerClass(ColorPicker,"ColorPicker");
Tomahawk.extend("ColorPicker","EventDispatcher");

ColorPicker.prototype._canvas = null;
ColorPicker.prototype._container = null;
ColorPicker.prototype.width = 1;
ColorPicker.prototype.height = 1;
ColorPicker.prototype._currentColor = "black";
ColorPicker.prototype._deployed = false;
ColorPicker.prototype._boxSize = 20;

ColorPicker.CHANGE_COLOR_EVENT = "changeColorEvent";


ColorPicker.prototype.init = function(container,width,height)
{
	var scope = this;
	var callback = function(event){ scope._clickHandler(event); };
	this._container = container;
	this._canvas = document.createElement("canvas");
	this._canvas.addEventListener("click", callback );
	this.width = width;
	this._canvas.style.border = "1px solid black";
	this.height = height;
	
	this._container.appendChild(this._canvas);
	this.refresh();
};

ColorPicker.prototype.getColor = function()
{
	return this._currentColor;
};

ColorPicker.prototype._clickHandler = function(event)
{
	var context = this._canvas.getContext("2d");
	var bounds = this._canvas.getBoundingClientRect();
	var x = parseInt(event.clientX - bounds.left);
	var y = parseInt(event.clientY - bounds.top);
	
	var data = context.getImageData(x,y,1,1).data;
	
	if( this._deployed == true )
	{
		var r = data[0].toString(16);
		var g = data[1].toString(16);
		var b = data[2].toString(16);
		var a = data[3].toString(16);
		
		r = ( r.length == 1 ) ? "0"+r : r;
		g = ( g.length == 1 ) ? "0"+g : g;
		b = ( b.length == 1 ) ? "0"+b : b;
		a = ( a.length == 1 ) ? "0"+a : a;
		this._currentColor = "#"+r+g+b;
		
		this.dispatchEvent(new tomahawk_ns.Event(ColorPicker.CHANGE_COLOR_EVENT,true,true));
	}

	this._deployed = !this._deployed;
	this.refresh();
};

ColorPicker.prototype.setColor = function(value)
{
	this._currentColor = value;
	this.refresh();
};

ColorPicker.prototype.refresh = function()
{
	var context = this._canvas.getContext("2d");
	
	if( this._deployed == true )
	{	
		this._canvas.width = this.width;
		this._canvas.height = this.height;
		var texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias("picker");
		context.clearRect(0,0,this._canvas.width,this._canvas.height);
		context.drawImage(	texture.data,
							texture.rect[0],
							texture.rect[1],
							texture.rect[2],
							texture.rect[3],
							0,
							0,
							this.width,
							this.height
							);
	}
	else
	{
		this._canvas.width = this._canvas.height = this._boxSize;
		context.clearRect(0,0,this._canvas.width, this._canvas.height);
		context.beginPath();
		context.fillStyle = this._currentColor;
		context.fillRect(0,0,this._boxSize,this._boxSize);
		context.fill();
	}
};




/**
 * ...
 * @author HTML5
 */

function Corner(textureName)
{
	var texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias(textureName);
	tomahawk_ns.Bitmap.apply(this, [texture]);
	
	this.mouseEnabled = this;
}

Tomahawk.registerClass( Corner, "Corner" );
Tomahawk.extend( "Corner", "Bitmap" );



/**
 * ...
 * @author Hatshepsout
 */

function ElementEditor(){}

ElementEditor.prototype._contrastButton 	= null;
ElementEditor.prototype._brightnessButton 	= null;
ElementEditor.prototype._alphaButton 		= null;
ElementEditor.prototype._currentElement 	= null;
ElementEditor.prototype._allowMoveButton 	= null;
ElementEditor.prototype._allowRotationButton= null;
ElementEditor.prototype._allowFiltersButton = null;
ElementEditor.prototype._allowResizeButton 	= null;
ElementEditor.prototype._allowChangeImage 	= null;
ElementEditor.prototype._resizeXButton 		= null;
ElementEditor.prototype._resizeYButton 		= null;
ElementEditor.prototype._resizeXYButton 	= null;
ElementEditor.prototype._clipLeftButton 	= null;
ElementEditor.prototype._clipRightButton 	= null;
ElementEditor.prototype._clipBottomButton 	= null;
ElementEditor.prototype._clipTopButton 		= null;

ElementEditor.prototype._borderButton 		= null;
ElementEditor.prototype._backgroundButton 	= null;
ElementEditor.prototype._colorPickerBorder 	= null;
ElementEditor.prototype._colorPickerBackground 	= null;

ElementEditor.prototype.setCurrentElement = function(value)
{
	this._currentElement = value;
	this.actualizeCheckboxes();
};

ElementEditor.prototype.actualizeCheckboxes = function()
{
	this._allowFiltersButton.checked = "";
	this._allowMoveButton.checked = "";
	this._clipBottomButton.checked = "";
	this._clipLeftButton.checked = "";
	this._clipRightButton.checked = "";
	this._clipTopButton.checked = "";
	this._allowResizeButton.checked = "";
	this._allowRotationButton.checked = "";
	this._allowChangeImage.checked = "";
	this._borderButton.checked = "";
	this._backgroundButton.checked = "";
	this._contrastButton.value = 0;
	this._brightnessButton.value = 0;
	this._alphaButton.value = 0;
	
	if( this._currentElement == null )
		return;
		
	this._contrastButton.value = this._currentElement.contrast;
	this._brightnessButton.value = this._currentElement.brightness;
	this._alphaButton.value = this._currentElement.alpha;
	
	if( this._currentElement.allowMove == true )
	{
		this._allowMoveButton.checked = "checked";
	}	
	
	if( this._currentElement.clipTop == true )
	{
		this._clipTopButton.checked = "checked";
	}
	
	if( this._currentElement.clipLeft == true )
	{
		this._clipLeftButton.checked = "checked";
	}
	
	if( this._currentElement.clipRight == true )
	{
		this._clipRightButton.checked = "checked";
	}
	
	if( this._currentElement.clipBottom == true )
	{
		this._clipBottomButton.checked = "checked";
	}
	
	if( this._currentElement.allowRotation == true )
	{
		this._allowRotationButton.checked = "checked";
	}
	
	if( this._currentElement.allowResize == true )
	{
		this._allowResizeButton.checked = "checked";
	}
	
	if( this._currentElement.allowFilters == true )
	{
		this._allowFiltersButton.checked = "checked";
	}
	
	if( this._currentElement.allowChangeImage == true )
	{
		this._allowChangeImage.checked = "checked";
	}
	
	if( this._currentElement.border == true )
	{
		this._borderButton.checked = "checked";
	}	
	
	if( this._currentElement.background == true )
	{
		this._backgroundButton.checked = "checked";
	}
	
	this._colorPickerBackground.setColor(this._currentElement.backgroundColor);
	this._colorPickerBorder.setColor(this._currentElement.borderColor);
};

ElementEditor.prototype.init = function()
{
	this._colorPickerBorder = new ColorPicker();
	this._colorPickerBackground = new ColorPicker();
	this._contrastButton = document.getElementById("contrastButton");
	this._brightnessButton = document.getElementById("brightnessButton");
	this._alphaButton = document.getElementById("alphaButton");
	this._allowMoveButton = document.getElementById("allowMove");
	this._allowRotationButton = document.getElementById("allowRotation");
	this._allowFiltersButton = document.getElementById("allowFilters");
	this._allowResizeButton = document.getElementById("allowResize");
	this._allowChangeImage = document.getElementById("allowChangeImage");
	this._resizeXButton = document.getElementById("resizeX");
	this._resizeYButton = document.getElementById("resizeY");
	this._resizeXYButton = document.getElementById("resizeXY");
	this._clipLeftButton = document.getElementById("clipLeft");
	this._clipTopButton = document.getElementById("clipTop");
	this._clipBottomButton = document.getElementById("clipBottom");
	this._clipRightButton = document.getElementById("clipRight");
	this._borderButton = document.getElementById("borderButton");
	this._backgroundButton = document.getElementById("backgroundButton");
	this._colorPickerBorder.init( document.getElementById("colorPickerContainerBorder"), 146,159 );
	this._colorPickerBorder.addEventListener( ColorPicker.CHANGE_COLOR_EVENT, this, this._borderEditHandler );
	
	this._colorPickerBackground.init( document.getElementById("colorPickerContainerBackground"), 146,159 );
	this._colorPickerBackground.addEventListener( ColorPicker.CHANGE_COLOR_EVENT, this, this._backgroundEditHandler );
	
	var scope = this;
	var callback = function(){
		scope._rightHandler.apply(scope,arguments);
	};
	this._contrastButton.onchange = callback;
	this._brightnessButton.onchange = callback;
	this._alphaButton.onchange = callback;
	this._allowMoveButton.addEventListener("click",callback);
	this._allowRotationButton.addEventListener("click",callback);
	this._allowFiltersButton.addEventListener("click",callback);
	this._allowResizeButton.addEventListener("click",callback);
	this._allowChangeImage.addEventListener("click",callback);
	this._resizeXButton.addEventListener("click",callback);
	this._resizeYButton.addEventListener("click",callback);
	this._resizeXYButton.addEventListener("click",callback);
	this._clipBottomButton.addEventListener("click",callback);
	this._clipLeftButton.addEventListener("click",callback);
	this._clipRightButton.addEventListener("click",callback);
	this._clipTopButton.addEventListener("click",callback);
	this._borderButton.addEventListener("click",callback);
	this._backgroundButton.addEventListener("click",callback);
};

ElementEditor.prototype._borderEditHandler = function(event)
{
	if( this._currentElement == null )
		return;
		
	this._currentElement.borderColor = this._colorPickerBorder.getColor();
};

ElementEditor.prototype._backgroundEditHandler = function(event)
{
	if( this._currentElement == null )
		return;
		
	this._currentElement.backgroundColor = this._colorPickerBackground.getColor();
	
	if( this._currentElement.refresh != undefined )
		this._currentElement.refresh();
};

ElementEditor.prototype._rightHandler = function(event)
{
	var checked = false;
	
	if( this._currentElement == null )
		return;
		
	checked = event.target.checked;
		
	switch( event.target )
	{
		case this._allowFiltersButton	: 	
			this._currentElement.allowFilters 	= checked; 
			this._currentElement.setContrast(this._currentElement.contrast);
			break;
		
		case this._contrastButton		: 	this._currentElement.setContrast( this._contrastButton.value );  break;
		case this._brightnessButton		: 	this._currentElement.setBrightness( this._brightnessButton.value ); break;
		case this._alphaButton			: 	this._currentElement.setAlpha( this._alphaButton.value ); break;
		case this._allowMoveButton		: 	this._currentElement.allowMove 		= checked; break;
		case this._allowResizeButton	: 	this._currentElement.allowResize 	= checked; break;
		case this._allowRotationButton	: 	this._currentElement.allowRotation 	= checked; break;
		case this._allowChangeImage		: 	this._currentElement.allowChangeImage = checked; break;
		case this._borderButton			: 	this._currentElement.border = checked; break;
		case this._backgroundButton		: 	this._currentElement.background = checked; break;
		case this._clipBottomButton		: 	this._currentElement.clipBottom = checked; break;
		case this._clipLeftButton		: 	this._currentElement.clipLeft = checked; break;
		case this._clipRightButton		: 	this._currentElement.clipRight = checked; break;
		case this._clipTopButton		: 	this._currentElement.clipTop = checked; break;
		
		case this._resizeXButton:
			if( this._currentElement.resizeByWidth != undefined )
			{
				this._currentElement.resizeByWidth();
			}
			break;
			
		case this._resizeYButton:
			if( this._currentElement.resizeByHeight != undefined )
			{
				this._currentElement.resizeByHeight();
			}
			break;
			
		case this._resizeXYButton:
			if( this._currentElement.resizeByHeight != undefined )
			{
				this._currentElement.fitSize();
			}
			break;
	}
	
	if( this._currentElement.refresh != undefined )
	{
		this._currentElement.refresh();
	}
	
	this.actualizeCheckboxes();
};





/**
 * note
 * @author Thot
 */

function MesureComponent()
{
	TransformableBitmap.apply(this);
	this._pointer = new Arrow();
	this._pointer.addEventListener("change", this, this._actualizeArrow);
	
	//dpe 55 - 12
	
	this.limits = new Array();
	this.limits.push(0); //A
	this.limits.push(67 / 454); // B
	this.limits.push(137 / 454 ); // C
	this.limits.push(201 / 454 ); // D
	this.limits.push(268 / 454 ); // E
	this.limits.push(335 / 454 ); // F
	this.limits.push(390 / 454 ); // G
	this.name = "MesureComponent";
	
	this._pointerPos = 0;
	this.addChild(this._pointer);
}

Tomahawk.registerClass( MesureComponent, "MesureComponent" );
Tomahawk.extend( "MesureComponent","TransformableBitmap" );

MesureComponent.RANGE_DPE					= [0,51,91,151,231,331,451];
MesureComponent.RANGE_GES					= [0,6,11,21,36,56,81];
MesureComponent.prototype.range				= [0,51,91,151,231,331,451];//default dpe
MesureComponent.prototype._pointer 			= null;
MesureComponent.prototype.limits 			= null;
MesureComponent.prototype._pointerPos 		= 0;

MesureComponent.prototype._actualizeArrow = function()
{
	var i = this.range.length;
	var value = this._pointer.getValue();
	
	while( --i > -1 )
	{
		if( value >= this.range[i] )
		{
			this._pointerPos = i;
			break;
		}
	}
	
	this.refresh();
};

MesureComponent.prototype._mouseHandler 	= function(event)
{
	if( event.type == tomahawk_ns.MouseEvent.DOUBLE_CLICK && event.target.isChildOf(this._pointer) )
	{
		this._pointer.select(true);
	}
	
	if(  event.type == tomahawk_ns.MouseEvent.MOUSE_DOWN && event.target == this._body )
	{
		this._pointer.select(false);
	}
	
	TransformableBitmap.prototype._mouseHandler.apply(this, [event] );
};

MesureComponent.prototype.refresh			= function()
{
	this.allowChangeImage = this.clipLeft = this.clipTop = this.clipRight = this.clipBottom = false;
	TransformableBitmap.prototype.refresh.apply(this);
	
	if( this._image == null )
		return;
	
	//this._pointer.setMask(this._region);
	var limit = this.limits[this._pointerPos];
	var naturalHeight = this._image.texture.rect[3];
	var naturalWidth = this._image.texture.rect[2];
	var ratioX = this._region.width / naturalWidth;
	var ratioY = this._region.height / naturalHeight;
	
	
	this._pointer.scaleX = ratioX;
	this._pointer.scaleY = ratioY;
	this._pointer.x = this._image.width - ( this._pointer.width * ratioX ) - 5;
	this._pointer.y = limit * this._image.height + this._image.y;
	
	
	this.addChild(this._pointer);
	//this.addChild(this._image);
};

MesureComponent.prototype.unserialize 		= function(obj)
{
	this.limits = obj.limits;
	this.range = obj.range;
	this._pointerPos = parseInt(obj.value);
	this._pointer.setValue( obj.realValue );
	TransformableBitmap.prototype.unserialize.apply(this,[obj]);
};

MesureComponent.prototype.serialize 		= function()
{
	var obj = TransformableBitmap.prototype.serialize.apply(this,[obj]);
	obj.type = "MesureComponent";
	obj.limits = this.limits;
	obj.range = this.range;
	obj.realValue = this._pointer.getValue();
	obj.realValue = ( isNaN( obj.realValue ) ) ? 0 : obj.realValue;
	obj.value = parseInt(this._pointerPos);
	return obj;
};










/**
 * ...
 * @author HTML5
 */

function Square()
{
	tomahawk_ns.Shape.apply(this);
}

Tomahawk.registerClass( Square, "Square" );
Tomahawk.extend( "Square", "Shape" );

Square.prototype.color = "black";

Square.prototype.draw = function(context)
{	
	this.clear();
	this.beginPath();
	this.fillStyle(this.color);
	this.fillRect(0,0,this.width,this.height);
	this.fill();
	this.closePath();
	
	//call super
	tomahawk_ns.Shape.prototype.draw.apply(this,[context]);
	
	this.mouseEnabled = true;
};



/**
 * ...
 * @author Hatshepsout
 */

function TextEditor(){}

TextEditor.prototype._sizeButton = null;
TextEditor.prototype._fontButton = null;
TextEditor.prototype._leftButton = null;
TextEditor.prototype._centerButton = null;
TextEditor.prototype._justifyButton = null;
TextEditor.prototype._rightButton = null;
TextEditor.prototype._italicButton = null;
TextEditor.prototype._colorPicker = null;
TextEditor.prototype._underlineButton = null;
TextEditor.prototype._container = null;
TextEditor.prototype._focusedTextField = null;
TextEditor.prototype._lastIndex = -1;

TextEditor.prototype.setCurrentTextField = function( textfield )
{
	this._focusedTextField = textfield;
	this.hide();
	
	if( this._focusedTextField != null )
	{
		this.display();
	}
};

TextEditor.prototype.init = function( elementId )
{
	this._container = document.getElementById(elementId);
	this._boldButton = document.getElementById('boldButton');
	this._italicButton = document.getElementById('italicButton');
	this._sizeButton = document.getElementById('sizeButton');
	this._fontButton = document.getElementById('fontButton');
	this._underlineButton = document.getElementById('underlineButton');
	this._leftButton = document.getElementById('leftButton');
	this._centerButton = document.getElementById('centerButton');
	this._justifyButton = document.getElementById('justifyButton');
	this._rightButton = document.getElementById('rightButton');
	this._colorPicker = new ColorPicker();
	this._colorPicker.init( document.getElementById("colorPickerContainer"), 146,159 );
	
	var scope = this;
	var callback = function(){
		scope._textEditHandler.apply(scope,arguments);
	};
	
	this._leftButton.onclick = callback;
	this._centerButton.onclick = callback;
	this._justifyButton.onclick = callback;
	this._rightButton.onclick = callback;
	this._boldButton.onclick = callback;
	this._italicButton.onclick = callback;
	this._underlineButton.onclick = callback;
	this._sizeButton.onchange = callback;
	this._fontButton.onchange = callback;
	this._colorPicker.addEventListener( ColorPicker.CHANGE_COLOR_EVENT, this, this._textEditHandler );
	
	this.refresh();
};

TextEditor.prototype.refresh = function()
{
	if( this._focusedTextField != null )
	{
		var index = this._focusedTextField.currentIndex;
		var textLength = this._focusedTextField.getText().length;
		var format = this._focusedTextField.defaultTextFormat;	
	
		if( textLength > 0 && index >= 0)
		{
			if( this._lastIndex != index )
			{
				format = this._focusedTextField.getTextFormat(index);
				this._colorPicker.setColor(format.textColor);
				this._sizeButton.value = parseInt(format.size);
				this._fontButton.value = format.font;
			}
		}
		else
		{
			this._sizeButton.value = parseInt(format.size);
			this._fontButton.value = format.font;
			this._colorPicker.setColor(format.textColor);
		}
			
		this._lastIndex = index;
	}
	
	setTimeout( this.refresh.bind(this), 500 );
};

TextEditor.prototype.display = function()
{
	//this._container.style.display = "block";
};

TextEditor.prototype.hide = function()
{
	//this._container.style.display = "none";
};

TextEditor.prototype._textEditHandler = function(event)
{
	if( this._focusedTextField == null )
		return;
		
	
	var range = this._focusedTextField.getSelectionRange();
	var start = range.start;
	var end = range.end;
	var currentFormat = null;
	var index = this._focusedTextField.currentIndex;
	
	
	switch( event.target )
	{
		case this._leftButton: this._focusedTextField.setTextAlign( tomahawk_ns.TextField.ALIGN_LEFT); break;
		case this._centerButton: this._focusedTextField.setTextAlign( tomahawk_ns.TextField.ALIGN_CENTER); break;
		case this._rightButton: this._focusedTextField.setTextAlign( tomahawk_ns.TextField.ALIGN_RIGHT); break;
		case this._justifyButton: this._focusedTextField.setTextAlign( tomahawk_ns.TextField.ALIGN_JUSTIFY); break;
	}
	
	if( start == -1 && end == -1 )
	{	
		currentFormat = this._focusedTextField.getTextFormat(index);
		
		switch( event.target )
		{
			case this._boldButton: currentFormat.bold = ( currentFormat.bold == true ) ? false : true; break;
			case this._italicButton: currentFormat.italic = ( currentFormat.italic == true ) ? false : true; break;
			case this._underlineButton: currentFormat.underline = ( currentFormat.underline == true ) ? false : true; break;
			case this._sizeButton: currentFormat.size = this._sizeButton.value; break;
			case this._fontButton: currentFormat.font = this._fontButton.value; break;
			case this._colorPicker: currentFormat.textColor = this._colorPicker.getColor(); break;
		}
		
		this._focusedTextField.setTextFormat(currentFormat,index,index);
		this._focusedTextField.defaultTextFormat = currentFormat.clone();
	}
	else
	{	
		for( ; start <= end; start++ )
		{
			currentFormat = this._focusedTextField.getTextFormat(start);
			
			switch( event.target )
			{
				case this._boldButton: currentFormat.bold = ( currentFormat.bold == true ) ? false : true; break;
				case this._italicButton: currentFormat.italic = ( currentFormat.italic == true ) ? false : true; break;
				case this._underlineButton: currentFormat.underline = ( currentFormat.underline == true ) ? false : true; break;
				case this._sizeButton: currentFormat.size = this._sizeButton.value; break;
				case this._fontButton: currentFormat.font = this._fontButton.value; break;
				case this._colorPicker: currentFormat.textColor = this._colorPicker.getColor(); break;
			}
			
			this._focusedTextField.setTextFormat(currentFormat,start,start);
		}
	}
};





/**
 * note
 * @author Thot
 */

function TransformableBitmap()
{
	TransformableObject.apply(this);
	this._region = new Square();
	this._region.width = 100;
	this._region.height = 100;
	this._region.alpha = 0.5;
	this.setBody(this._region);
	
	this._info = new tomahawk_ns.TextField();
	this._info.defaultTextFormat.fontSize = 8;
	this._info.width = 80;
	this._info.height = 100;
	this._info.x = this._info.y = 10;
	this._info.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
	//this._info.setText("Zone Image              Double-cliquez pour ajouter une image");
	this._info.setText(Localization.getInstance().getLabel("ZONE_IMAGE"));
	this._info.mouseEnabled = false;
	this.addChild(this._info);
}

Tomahawk.registerClass( TransformableBitmap, "TransformableBitmap" );
Tomahawk.extend( "TransformableBitmap","TransformableObject" );

TransformableBitmap.prototype._info 			= null;
TransformableBitmap.prototype._image 			= null;
TransformableBitmap.prototype._region 			= null;
TransformableBitmap.prototype._border 			= null;
TransformableBitmap.prototype._back 			= null;
TransformableBitmap.prototype.border 			= true;
TransformableBitmap.prototype.borderColor 		= "black";
TransformableBitmap.prototype.allowFilters 		= true;
TransformableBitmap.prototype.allowChangeImage  = true;

TransformableBitmap.prototype.clipTop  			= true;
TransformableBitmap.prototype.clipLeft  		= true;
TransformableBitmap.prototype.clipBottom  		= true;
TransformableBitmap.prototype.clipRight  		= true;

TransformableBitmap.prototype._dblClickHandler = function(event)
{
	this._fileReader = new ImageFileReader();
	this._fileReader.addEventListener( EditorEvent.IMAGE_LOADED, this, this._imageLoadHandler );
	this._fileReader.start();
};

TransformableBitmap.prototype._imageLoadHandler = function(event)
{
	var img = event.image;
	var file = event.file;
	var data = ImageResizer.resize ( img );
	var scope = this;
	var event = new EditorEvent(EditorEvent.USER_IMAGE_ADDED,true,true);
	var texture = null;
	var scope = this;

	event.data = new Object();
	
	img.onload = function()
	{
		event.data.data = data;
		event.data.name = file.name;
		
		var specialChars = "!@#$^&%*()+=-[]\/{}|:<>?,° ";
		for (var i = 0; i < specialChars.length; i++) {
			event.data.name = event.data.name.replace(new RegExp("\\" + specialChars[i], 'gi'), '_');
		}
		
		texture =  new tomahawk_ns.Texture();
		texture.data =  img;
		texture.rect = [0,0,img.width,img.height];
		texture.name = event.data.name;
		tomahawk_ns.AssetsManager.getInstance().addTexture(texture,texture.name);
		
		scope.setTexture(texture);
		scope.dispatchEvent(event);
	};
	
	img.src = data;
};

TransformableBitmap.prototype._mouseHandler 	= function(event)
{
	TransformableObject.prototype._mouseHandler.apply(this, [event] );
	if( event.type == tomahawk_ns.MouseEvent.DOUBLE_CLICK && this.allowChangeImage )
	{
		this._dblClickHandler(event);
		return;
	}
	
	this.refresh();
};

TransformableBitmap.prototype.setTexture 		= function(texture)
{
	if( this._info != null )
	{
		this._info.destroy();
		this._info = null;
	}
	
	if( this._image == null )
	{
		this._image = new tomahawk_ns.Bitmap(texture);
	}
	else
	{
		this.removeChild(this._image);
		this._image.texture = texture;
	}
	
	this._image.width = this._region.width;
	this._image.height = this._region.height;
	
	
	this._region.alpha = 1;
	this._image.setMask(this._region);
	this.addChild(this._image);
	this.setBody(this._region);
	
	this.refresh();
};

TransformableBitmap.prototype.resize = function(width,height)
{
	this._region.width = width;
	this._region.height = height;
	this.refresh();
};

TransformableBitmap.prototype.refresh			= function()
{
	if( this._image == null )
		return;
	
	var naturalHeight = this._image.texture.rect[3];
	var naturalWidth = this._image.texture.rect[2];
	var ratioX = this._region.width / naturalWidth;
	var ratioY = this._region.height / naturalHeight;
	var ratio = ( ratioX > ratioY ) ? ratioX : ratioY;
	var width = naturalWidth * ratio;
	var height = naturalHeight * ratio;
	var diffX = this._region.width - width;
	var diffY = this._region.height - height;
	var x = 0; 
	var y = 0;
	
	if( this.clipLeft == false && this.clipRight == false )
	{
		width = this._region.width;
		x = 0;
	}
	else if( this.clipLeft == true && this.clipRight == true )
	{
		x = diffX * 0.5;
	}
	else if( this.clipLeft == true )
	{
		x = diffX;
	}
	else
	{
		x = 0;
	}
	
	if( this.clipTop == false && this.clipBottom == false )
	{
		height = this._region.height;
		y = 0;
	}
	else if( this.clipTop == true && this.clipBottom == true )
	{
		y = diffY * 0.5;
	}
	else if( this.clipTop == true )
	{
		y = diffY;
	}
	else
	{
		y = 0;
	}
	
	this._image.x = x;
	this._image.y = y;
	this._image.width = width; 
	this._image.height = height; 
	
	if( this._image.cacheAsBitmap == true )
	{
		this._image.updateCache();
		this._image.cacheAsBitmap = false;
	}
	
	this._replaceCorners();
};

TransformableBitmap.prototype.resizeByHeight 	= function()
{
	if( this._image == null )
		return;
		
	var naturalHeight = this._image.texture.rect[3];
	var naturalWidth = this._image.texture.rect[2];
	var naturalRatio = naturalHeight / naturalWidth;
	
	this._image.height = this._region.height;
	this._image.width = this._image.height / naturalRatio; 
	
	this._region.width = this._image.width;
	this._region.height = this._image.height;

	this._region.x = this._image.x = this._region.y = this._image.y = 0;
	this.clipTop = this.clipBottom = this.clipLeft = this.clipRight = true;
	this._drawBorderAndBackground();
	this._replaceCorners();
	
	if( this._image.cacheAsBitmap == true )
	{
		this._image.updateCache();
	}
};

TransformableBitmap.prototype.fitSize = function()
{
	if( this._image == null )
		return;
	
	this._image.width = this._region.width;
	this._image.height = this._region.height; 
	
	
	this._region.x = this._image.x = this._region.y = this._image.y = 0;
	this.clipTop = this.clipBottom = this.clipLeft = this.clipRight = false;
	
	this._drawBorderAndBackground();
	this._replaceCorners();
	
	if( this._image.cacheAsBitmap == true )
	{
		this._image.updateCache();
	}
};

TransformableBitmap.prototype.resizeByWidth 	= function()
{
	if( this._image == null )
		return;
		
	var naturalHeight = this._image.texture.rect[3];
	var naturalWidth = this._image.texture.rect[2];
	var naturalRatio = naturalWidth / naturalHeight;
	
	this._image.width = this._region.width;
	this._image.height = this._image.width / naturalRatio; 
	
	this._region.width = this._image.width;
	this._region.height = this._image.height;
	
	this._region.x = this._image.x = this._region.y = this._image.y = 0;
	this.clipTop = this.clipBottom = this.clipLeft = this.clipRight = true;
	this._drawBorderAndBackground();
	this._replaceCorners();
	
	if( this._image.cacheAsBitmap == true )
	{
		this._image.updateCache();
	}
};

TransformableBitmap.prototype.unserialize 		= function(obj)
{
	var texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias(obj.textureName);
	
	TransformableObject.prototype.unserialize.apply(this,[obj]);
	this.allowFilters 	= obj.allowFilters;
	this.allowChangeImage = obj.allowChangeImage;
			
	if( texture != null )
	{
		this.setTexture(texture);
		this.setContrast(obj.contrast);
		this.setBrightness(obj.brightness);
	}
};

TransformableBitmap.prototype.serialize 		= function()
{
	var obj = TransformableObject.prototype.serialize.apply(this,[obj]);
	obj.type = "TransformableBitmap";
	obj.textureName = ( this._image == null ) ? null : this._image.texture.name;
	obj.allowFilters = this.allowFilters;
	obj.allowChangeImage = this.allowChangeImage;
	
	return obj;
};

TransformableBitmap.prototype._addFilters = function()
{
	if( this._image == null )
		return;
		
	this._image.filters = null;
	this._image.cacheAsBitmap = false;
	this.alpha = 1;
	
	if( this.allowFilters == false )
		return;
	
	this.alpha = this._alpha;
	
	var filters = new Array();
	var filt = null;
	
	if( this.contrast != 0 )
	{
		filt = new ContrastFilter();
		filt.value = this.contrast;
		filters.push(filt);
	}
	
	if( this.brightness != 0 )
	{
		filt = new BrightnessFilter();
		filt.value = this.brightness;
		filters.push(filt);
	}
	
	
	if( filters.length > 0 )
	{
		this._image.filters = filters;
		this._image.cacheAsBitmap = true;
		this._image.updateCache();
	}
};

TransformableBitmap.prototype.setBrightness = function(value)
{
	TransformableObject.prototype.setBrightness.apply(this,[value]);
	this._addFilters();
};

TransformableBitmap.prototype.setContrast = function(value)
{
	TransformableObject.prototype.setContrast.apply(this,[value]);
	this._addFilters();
};

TransformableBitmap.prototype.setAlpha = function(value)
{
	TransformableObject.prototype.setAlpha.apply(this,[value]);
	this._addFilters();
};

TransformableBitmap.prototype._replaceCorners 	= function()
{
	TransformableObject.prototype._replaceCorners.apply(this);
	
	if( this._info != null && this._region != null )
	{
		this._info.x = ( this._region.width - this._info.width ) >> 1;
		this._info.y = ( this._region.height - this._info.height ) >> 1;
	}
};




/**
 - suppression
 - resize
 - rotation
 - clonage
 - editer les textes au double click
 - ajouter la save 
 - possibilité de paramétrer le pas de la rotation

 * note
 * @author Thot
 */

function TransformableObject()
{
	tomahawk_ns.Sprite.apply(this);
	this.init(0,0,100,100);
}

Tomahawk.registerClass( TransformableObject, "TransformableObject" );
Tomahawk.extend( "TransformableObject", "Sprite" );

TransformableObject.prototype.minWidth 		= 20;
TransformableObject.prototype.minHeight 	= 20;
TransformableObject.prototype._body 		= null;
TransformableObject.prototype._corner1 		= null;
TransformableObject.prototype._corner2 		= null;
TransformableObject.prototype._corner3 		= null;
TransformableObject.prototype._corner4 		= null;
TransformableObject.prototype._active 		= false;
TransformableObject.prototype._activeObject = null;
TransformableObject.prototype.border 		= true;
TransformableObject.prototype.background 	= true;
TransformableObject.prototype.borderColor 	= "#000000";
TransformableObject.prototype.backgroundColor = "#ffffff";
TransformableObject.prototype.contrast 		= 0;
TransformableObject.prototype.brightness 	= 0;
TransformableObject.prototype._alpha 		= 1;

TransformableObject.prototype.allowDelete 		= true;
TransformableObject.prototype.allowResize 		= true;
TransformableObject.prototype.allowRotation 	= true;
TransformableObject.prototype.allowMove 		= true;

TransformableObject.prototype.init 				= function(x,y,width,height)
{
	this._border = new tomahawk_ns.Shape();
	this._back = new tomahawk_ns.Shape();
	
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	
	this._corner1	= new Corner('cross');
	this._corner2	= new Corner('rotation');
	this._corner3	= new Corner('resize');
	this._corner4	= new Corner('up');
	
	this._corner1.width = this._corner1.height = 20;
	this._corner2.width = this._corner2.height = 20;
	this._corner3.width = this._corner3.height = 20;
	this._corner4.width = this._corner4.height = 20;
	this._hasBorder = false;
	
	this.mouseEnabled = true;
	
	if( this._body == null )
	{
		var body = this._buildShape("white",width,height);
		body.width = this.width;
		body.height = this.height;
		this.setBody(body);
	}
	
	this.setActive(false);	
	this._back.mouseEnabled = this._border.mouseEnabled = false;
};

TransformableObject.prototype.getBody 			= function()
{
	return this._body;
};

TransformableObject.prototype.setActive 		= function(value)
{
	this._active = value;
	
	tomahawk_ns.Stage.getInstance().removeEventListener(tomahawk_ns.MouseEvent.MOUSE_UP, this,this._mouseHandler, true);
	tomahawk_ns.Stage.getInstance().removeEventListener(tomahawk_ns.MouseEvent.MOUSE_MOVE,this,this._mouseHandler, true);
	tomahawk_ns.Stage.getInstance().removeEventListener(tomahawk_ns.MouseEvent.DOUBLE_CLICK, this,this._mouseHandler, true);
	tomahawk_ns.Stage.getInstance().removeEventListener(tomahawk_ns.MouseEvent.CLICK, this,this._mouseHandler, true);
	
	this.removeEventListener(tomahawk_ns.MouseEvent.MOUSE_DOWN, this,this._mouseHandler, true);
	this.removeEventListener(tomahawk_ns.MouseEvent.ROLL_OVER, this,this._mouseHandler, true);
	
	tomahawk_ns.Stage.getInstance().addEventListener(tomahawk_ns.MouseEvent.CLICK, this,this._mouseHandler, true);
	this.addEventListener(tomahawk_ns.MouseEvent.MOUSE_DOWN, this,this._mouseHandler, true);
	
	if( this._active == true )
	{
		tomahawk_ns.Stage.getInstance().addEventListener(tomahawk_ns.MouseEvent.DOUBLE_CLICK, this,this._mouseHandler, true);
		tomahawk_ns.Stage.getInstance().addEventListener(tomahawk_ns.MouseEvent.MOUSE_UP, this,this._mouseHandler, true);
		tomahawk_ns.Stage.getInstance().addEventListener(tomahawk_ns.MouseEvent.MOUSE_MOVE, this,this._mouseHandler, true);
		this.addEventListener(tomahawk_ns.MouseEvent.ROLL_OVER, this,this._mouseHandler, true);
	}
	
	var type = (this._active == true) ? EditorEvent.SELECT_OBJECT : EditorEvent.UNSELECT_OBJECT;
	this.dispatchEvent( new EditorEvent(type,true,true) );
};

TransformableObject.prototype.setBody 			= function(body)
{
	if( this._body != null )
	{
		this._body._listeners = new Array();
		this.removeChild(this._body);
	}
	
	this._body = body;
	
	if( this._body != null )
	{
		//this._body.width = this.width;
		//this._body.height = this.height;
		this._body.mouseEnabled = true;
		this.addChild(this._body);
	}
};

TransformableObject.prototype._replaceCorners 	= function()
{
	if( this._body == null )
		return;
		
	var offset = this._corner1.width >> 1;
	if( this.name == "background" )
		offset = 0;
		
	var cornerWidth = this._corner1.width;
	
	if( this._active == true )
	{
		this.addChild(this._corner1);
		this.addChild(this._corner2);
		this.addChild(this._corner3);
		this.addChild(this._corner4);
		
		this._corner1.x = this._corner4.x = -offset;
		this._corner1.y = this._corner2.y = -offset;
		this._corner3.x = this._corner2.x = this._body.width - cornerWidth + offset;
		this._corner3.y = this._corner4.y = this._body.height - cornerWidth + offset;
	}
	else
	{
		this.removeChild(this._corner1);
		this.removeChild(this._corner2);
		this.removeChild(this._corner3);
		this.removeChild(this._corner4);
	}
	
	this._corner1.visible = this.allowDelete;
	this._corner2.visible = this.allowRotation;
	this._corner3.visible = this.allowResize;
};

TransformableObject.prototype._mouseHandler 	= function(event)
{	
	Mouse.setCursor(Mouse.DEFAULT);
	
	if( event.type == tomahawk_ns.MouseEvent.ROLL_OVER || event.type == tomahawk_ns.MouseEvent.MOUSE_MOVE)
	{
		if( event.target == this._corner1 )
			Mouse.setCursor(Mouse.KILL);
			
		if( event.target == this._corner2 )
			Mouse.setCursor(Mouse.ROTATE);
			
		if( event.target == this._corner3 )
			Mouse.setCursor(Mouse.RESIZE);
			
		if( event.target == this._body )
			Mouse.setCursor(Mouse.DRAG);
	}
	
	if( ( event.type == tomahawk_ns.MouseEvent.CLICK ) || ( event.type == tomahawk_ns.MouseEvent.MOUSE_DOWN ) )
	{
		this.setActive(event.target == this || event.target.isChildOf(this));
		this._replaceCorners();
		this._activeObject = null;
	}
	
	if( this._active == false )
		return;
	
	if( event.type == tomahawk_ns.MouseEvent.MOUSE_DOWN )
	{
		this._activeObject = event.target;
	}
		
	if( event.type == tomahawk_ns.MouseEvent.MOUSE_UP )
	{
		this._activeObject = null;
	}

	// transform
	if( this._activeObject == null )
		return;
		
	var coords = this.globalToLocal(event.stageX,event.stageY);
	var pt1 = null;
	var pt2 = null;
	
	if( this._activeObject == this._body && this.allowMove == true ) // drag
	{
		Mouse.setCursor(Mouse.DRAG);
		var pt = tomahawk_ns.Stage.getInstance().getMovement();
		this.x += pt.x;
		this.y += pt.y;
	}
	
	if( this._activeObject == this._corner1 && this.allowDelete == true )// kill the object
	{
		Mouse.setCursor(Mouse.KILL);
		if( this.parent != null )
		{
			this.parent.removeChild(this);
			return;
		}
	}
	
	if( this._activeObject == this._corner2 && this.allowRotation == true ) // rotate
	{
		Mouse.setCursor(Mouse.ROTATE);
		coords = this.localToGlobal(0, 0 );
		
		var dx = event.stageX - coords.x;
		var dy = event.stageY - coords.y;
		var angleRadian = Math.atan2( dy, dx );
		var angleDegree = Math.floor(angleRadian * ( 180 / Math.PI ));
		this.rotation = parseInt(angleDegree / 10) * 10;
	}
	
	if( this._activeObject == this._corner3 && this.allowResize == true ) // resize
	{
		Mouse.setCursor(Mouse.RESIZE);
		
		if( this.name == "background" )
		{
			var distanceX = coords.x - this._corner1.x + this._corner1.width * 0.5;
			var distanceY = coords.y - this._corner1.y + this._corner1.height * 0.5;
		}
		else
		{
			var distanceX = coords.x - this._corner1.x - this._corner1.width * 0.5;
			var distanceY = coords.y - this._corner1.y - this._corner1.height * 0.5;
		}
		this._body.width = ( distanceX < this.minWidth ) ? this.minWidth : distanceX;
		this._body.height = ( distanceY < this.minHeight ) ? this.minHeight : distanceY;
	}
	
	if( this._activeObject == this._corner4 && this.parent != null ) // childindex + 1
	{
		var index = this.parent.getChildIndex(this);
		this.parent.setChildIndex(this,index+1);
	}
	
	
	this._replaceCorners();
};

TransformableObject.prototype._buildShape 		= function(color,width,height)
{
	var shape = new Square();
	shape.width = width;
	shape.height = height;
	shape.color = color;
	shape.mouseEnabled = true;
	return shape;
};

TransformableObject.prototype._drawBorderAndBackground 		= function()
{
	this._border.clear();
	this._back.clear();
	
	if( this.border == true )
	{	
		this._border.width = this._body.width;
		this._border.height = this._body.height;
		this._border.x = this._body.x;
		this._border.y = this._body.y;
		
		
		this._border.clear();
		this._border.beginPath();
		this._border.strokeStyle(this.borderColor);
		this._border.lineWidth(2);
		this._border.moveTo( this._body.x , this._body.y );
		this._border.lineTo( this._body.x + this._body.width, this._body.y );
		this._border.lineTo( this._body.x + this._body.width, this._body.y + this._body.height );
		this._border.lineTo( this._body.x , this._body.y + this._body.height );
		this._border.lineTo( this._body.x , this._body.y );
		this._border.stroke();
		this._border.closePath();
	}
	
	if( this.background == true )
	{
		this._back.beginPath();
		this._back.fillStyle(this.backgroundColor);
		this._back.fillRect(this._body.x, this._body.y, this._body.width, this._body.height);
		this._back.fill();
		this._back.closePath();
	}
	
	this.addChildAt(this._back,0);
	this.addChild(this._border);
	this._replaceCorners();
};

TransformableObject.prototype.draw = function(context)
{	
	this._drawBorderAndBackground();
	tomahawk_ns.Sprite.prototype.draw.apply(this,[context]);
};

TransformableObject.prototype.unserialize = function(obj)
{
	

	this.border = obj.border;
	this.borderColor = obj.borderColor;
	this.background = obj.background;
	this.backgroundColor = obj.backgroundColor;
	this.allowRotation = obj.allowRotation;
	this.allowResize = obj.allowResize;
	this.allowMove = obj.allowMove;
	this.x = obj.x;
	this.y = obj.y;
	this.rotation = obj.rotation;
	this._body.width = obj.width;
	this._body.height = obj.height;
	this.minWidth = obj.minWidth;
	this.minHeight = obj.minHeight;
	this.name = obj.name;

	this.setContrast(obj.contrast);
	this.setBrightness(obj.brightness);
	this.setAlpha(obj.alpha);
	
	
	this._replaceCorners();
};

TransformableObject.prototype.serialize = function()
{
	var obj = new Object();
	obj.type = "TransformableObject";
	obj.border = this.border;
	obj.borderColor = this.borderColor;
	obj.background = this.background;
	obj.backgroundColor = this.backgroundColor;
	obj.allowRotation = this.allowRotation;
	obj.allowMove = this.allowMove;
	obj.allowResize = this.allowResize;
	obj.width = this._body.width;
	obj.height = this._body.height;
	obj.x = this.x;
	obj.y = this.y;
	obj.rotation = this.rotation;
	obj.minWidth = this.minWidth;
	obj.minHeight = this.minHeight;
	obj.hasBorder = this._hasBorder;
	obj.contrast = this.contrast;
	obj.brightness = this.brightness;
	obj.name = this.name;
	obj.alpha = this._alpha;
	
	return obj;
};

TransformableObject.prototype.setContrast = function(value)
{
	this.contrast =  parseInt(value);
};

TransformableObject.prototype.setBrightness = function(value)
{
	this.brightness =  parseInt(value);
};

TransformableObject.prototype.setAlpha = function(value)
{
	this._alpha = parseFloat(value);
};







/**
 * note
 * @author Thot
 */

function TransformableText(defaultTextFormat)
{
	TransformableObject.apply(this);
	
	var field = new tomahawk_ns.InputTextField();
	
	if( defaultTextFormat != undefined )
	{
		field.defaultTextFormat = defaultTextFormat;
	}
	field.padding = 10;
	field.background = false;
	field.border = false;
	this.setBody(field);
	this._field = field;	
	this._field.name = "text"
}

Tomahawk.registerClass( TransformableText, "TransformableText" );
Tomahawk.extend( "TransformableText","TransformableObject" );

TransformableText.ID = 0;
TransformableText.prototype._field = null;
TransformableText.prototype.isText = true;

TransformableText.prototype.setText 		= function(text)
{
	this._field.setText(text);
};

TransformableText.prototype.setTextAlign = function(value)
{
	this._field.setTextAlign(value);
};

TransformableText.prototype.autoFocus = function()
{
	this.setActive(true);
	this._replaceCorners();
	this._activeObject = null;
	this._field.setFocus(true);
};

TransformableText.prototype._mouseHandler 	= function(event)
{	
	if( event.type != tomahawk_ns.MouseEvent.MOUSE_MOVE && 
		event.target != this._field 
	)
	{
		this._field.setFocus(false);
	}
	
	if( 	event.type == tomahawk_ns.MouseEvent.DOUBLE_CLICK 					&& 
			this._field.getFocus() == false 									&& 
			( event.target == this._field || event.target.isChildOf(this._field) ) 
	)
	{
		this._field.setFocus(true);
		this._field._setIndexUnderMouse(event.stageX,event.stageY);
	}
	
	if( this._field.getFocus() == false )
	{
		TransformableObject.prototype._mouseHandler.apply( this, [event] );
	}
};

TransformableText.prototype.unserialize 	= function(obj)
{
	TransformableObject.prototype.unserialize.apply(this,[obj]);
	this._field.setText(obj.text);
	this._field.defaultTextFormat.textColor = obj.defaultTextFormat[0];
	this._field.defaultTextFormat.underline = obj.defaultTextFormat[1];
	this._field.defaultTextFormat.backgroundSelectedColor = obj.defaultTextFormat[2];
	this._field.defaultTextFormat.font = obj.defaultTextFormat[3];
	this._field.defaultTextFormat.bold = obj.defaultTextFormat[4];
	this._field.defaultTextFormat.italic = obj.defaultTextFormat[5];
	this._field.defaultTextFormat.size = obj.defaultTextFormat[6];
	
	var i = obj.formats.length;
	var format = null;
	var formatDesc = null;
	
	while( --i > -1 )
	{
		formatDesc = obj.formats[i];
		format = new tomahawk_ns.TextFormat();
		
		format.textColor = formatDesc[0];
		format.underline = formatDesc[1];
		format.backgroundSelectedColor = formatDesc[2];
		format.font = formatDesc[3];
		format.bold = formatDesc[4];
		format.italic = formatDesc[5];
		format.size = formatDesc[6];
		
		this._field.setTextFormat(format,i,i);
	}
	
	this._field.setTextAlign(obj.align);
};

TransformableText.prototype.serialize 		= function()
{
	var obj = TransformableObject.prototype.serialize.apply(this,[obj]);
	var text = this._field.getText();
	var format = null;
	var i = text.length;
	var formatDesc = null;
	
	obj.type = "TransformableText";
	obj.text = text;
	obj.align = this._field.getTextAlign();
	obj.formats = new Array();
	obj.defaultTextFormat = new Array();
	obj.defaultTextFormat[0] = this._field.defaultTextFormat.textColor;
	obj.defaultTextFormat[1] = this._field.defaultTextFormat.underline;
	obj.defaultTextFormat[2] = this._field.defaultTextFormat.backgroundSelectedColor;
	obj.defaultTextFormat[3] = this._field.defaultTextFormat.font;
	obj.defaultTextFormat[4] = this._field.defaultTextFormat.bold;
	obj.defaultTextFormat[5] = this._field.defaultTextFormat.italic;
	obj.defaultTextFormat[6] = this._field.defaultTextFormat.size;
	
	while( --i > -1 )
	{
		format = this._field.getTextFormat(i);
		formatDesc = new Array();
		formatDesc[0] = format.textColor;
		formatDesc[1] = format.underline;
		formatDesc[2] = format.backgroundSelectedColor;
		formatDesc[3] = format.font;
		formatDesc[4] = format.bold;
		formatDesc[5] = format.italic;
		formatDesc[6] = format.size;
		obj.formats.unshift(formatDesc);
		
		
		console.log(i,obj.text[i]);
	}
	
	return obj;
};

TransformableText.prototype.resize = function(width,height)
{
	this._body.width = width;
	this._body.height = height;
};

TransformableText.prototype.refreshTextField = function()
{
	this._field._refreshNextFrame = true;
	var i = this._field.children.length;
	var word = null;
	
	while( --i > -1 )
	{
		word = this._field.children[i];
		word.needRefresh = true;
		word.smooth = true;
	}
};

TransformableText.prototype.magnify = function(scale)
{
	var canvas = document.createElement("canvas");
	var context = canvas.getContext("2d");
	var magnifier = 2;
	var texture = new tomahawk_ns.Texture();
	var bmp = null;
	
	this._body.width *= scale * magnifier;
	this._body.height *= scale * magnifier;
	
	this._field.scaleX = scale * magnifier;
	this._field.scaleY = scale * magnifier;
	
	canvas.width = this._body.width;
	canvas.height = this._body.height;
	
	this.draw(context);
	
	this.scaleX = 1 / magnifier;
	this.scaleY = 1 / magnifier;
	
	texture.data = canvas;
	texture.rect = [0,0,canvas.width,canvas.height];
	texture.name = "";
	
	bmp = new tomahawk_ns.Bitmap(texture);
	this.removeChildren();
	this.addChild(bmp);
};







/**
 * @author The Tiny Spark
 */
	function EditorEvent()
	{
		tomahawk_ns.Event.apply(this);
	}

	Tomahawk.registerClass( EditorEvent, "EditorEvent" );
	Tomahawk.extend( "EditorEvent", "Event" );

	function EditorEvent(type, bubbles, cancelable)
	{
		this.type = type;
		this.cancelable = cancelable;
		this.bubbles = bubbles;
	}

	EditorEvent.SELECT_OBJECT 		= "selectObject";
	EditorEvent.UNSELECT_OBJECT 	= "unselectObject";
	EditorEvent.IMAGE_LOADED 		= "imageLoaded";
	EditorEvent.IMAGE_SAVED 		= "imageSaved";
	EditorEvent.USER_IMAGE_ADDED 	= "userImageAdded";



	function BrightnessFilter()
	{
		tomahawk_ns.PixelFilter.apply(this);
	}
	
	Tomahawk.registerClass( BrightnessFilter, "BrightnessFilter" );
	Tomahawk.extend( "BrightnessFilter", "PixelFilter" );
	
	BrightnessFilter.prototype.value = 0;

	BrightnessFilter.prototype.process = function()
	{
		if( this.value == 0 )
			return;
			
		var pixels = this.getPixels(0,0,this._canvas.width,this._canvas.height);
		var data = pixels.data;
		var value = parseInt(this.value);
		
		for (var i=0; i<data.length; i+=4) 
		{
			data[i]	  = data[i] + value;
			data[i+1] = data[i+1] + value;
			data[i+2] = data[i+2] + value;
		}
		
		this.setPixels(pixels,0,0);
	};




	function ContrastFilter()
	{
		tomahawk_ns.PixelFilter.apply(this);
	}
	
	Tomahawk.registerClass( ContrastFilter, "ContrastFilter" );
	Tomahawk.extend( "ContrastFilter", "PixelFilter" );
	
	ContrastFilter.prototype.value = 0;

	ContrastFilter.prototype.process = function()
	{
		if( this.value == 0 )
			return;
			
		var pixels = this.getPixels(0,0,this._canvas.width,this._canvas.height);
		var data = pixels.data;
		var r = 0, g = 0, b = 0, a = 0;
		var value = parseFloat(this.value);

		for (var i=0; i<data.length; i+=4) 
		{
			r = data[i+0]; r/=255; r -= 0.5; r *= value; r += 0.5; r *= 255;
			g = data[i+1]; g/=255; g -= 0.5; g *= value; g += 0.5; g *= 255;
			b = data[i+2]; b/=255; b -= 0.5; b *= value; b += 0.5; b *= 255;
			
			r = parseInt(r); r = ( r > 255 ) ? 255 : r; r = ( r < 0 ) ? 0 : r;
			g = parseInt(g); g = ( g > 255 ) ? 255 : g; g = ( g < 0 ) ? 0 : g;
			b = parseInt(b); b = ( b > 255 ) ? 255 : b; b = ( b < 0 ) ? 0 : b;
			
			data[i] = r;
			data[i+1] = g;
			data[i+2] = b;
		}
		
		this.setPixels(pixels,0,0);
	};




/**
 * ...
 * @author Hatshepsout
 */

function FicheSaver(){}

FicheSaver.onComplete = null;

FicheSaver.save = function(url,data,preview)
{
	var http = new XMLHttpRequest();
	var url = url;
	var params = "data="+data+"&preview="+preview;
	var scope = this;
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//http.setRequestHeader("Content-length", params.length);
	//http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			if( scope.onComplete != null )
			{
				scope.onComplete(http.responseText);
			}
		}
	}
	http.send(params);
};



/**
 * ...
 * @author Hatshepsout
 */

function ImageFileReader()
{
	this._init();
}

Tomahawk.registerClass( ImageFileReader, "ImageFileReader" );
Tomahawk.extend( "ImageFileReader", "EventDispatcher" );

ImageFileReader.prototype._element = null;

ImageFileReader.prototype._init = function()
{
	this._element = document.createElement("input");
	this._element.type = "file";
	this._element.style.visibility = "hidden";
	this._element.addEventListener('change', this._handleFileSelect.bind(this), false);
};

ImageFileReader.prototype.start = function()
{
	var element = this._element;
	document.body.appendChild(element);
	element.click();
	//
    //if (document.createEventObject){
		//
        // dispatch for IE
        //var evt = document.createEventObject();
        //element.fireEvent('onclick',evt)
    //}
    //else{
        // dispatch for firefox + others
        //var evt = document.createEvent("HTMLEvents");
        //evt.initEvent("click", true, true ); // event type,bubbling,cancelable
        //element.dispatchEvent(evt);
    //}
};

ImageFileReader.prototype._handleFileSelect = function(event)
{
	var files = event.target.files; // FileList object
	var currentFile = null;
	var max = files.length;
	var i = 0;
	var reader = null;
	    
	// Loop through the FileList and render image files as thumbnails.
    for (i = 0; i < max; i++) 
	{
		currentFile = files[i]
		// Only process image files.
		
		if (!currentFile.type.match('image.*'))
			continue;

		reader = new FileReader();
		reader.onload= this._readFileHandler.bind(this,reader,currentFile);

		// Read in the image file as a data URL.
		reader.readAsDataURL(currentFile);
    }
};

ImageFileReader.prototype._readFileHandler = function(reader,file)
{
	var img = new Image();
	img.onload = this._imageLoadedHandler.bind(this,img,file,reader);
	img.src = reader.result;
};

ImageFileReader.prototype._imageLoadedHandler = function(img,file,reader)
{
	var event = new EditorEvent(EditorEvent.IMAGE_LOADED,true,true);
	event.image = img;
	event.file = file;
	event.data = reader.result;
	this.dispatchEvent( event );
	document.body.removeChild(this._element);
};

ImageFileReader.prototype.createDOMElement = function(id,name)
{
	var el = document.createElement("input");
	el.type = "file";
	el.id = id;
	el.name = name;
	el.multiple = true;
	
	return el;
};






function ImageFileSaver(){}

ImageFileSaver.onComplete = null;

ImageFileSaver.save = function(url,data,name,ficheId)
{
	var http = new XMLHttpRequest();
	var url = url;
	var params = "name="+name+"&data="+data;
	var scope = this;
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//http.setRequestHeader("Content-length", params.length);
	//http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			
			if( scope.onComplete != null )
			{
				scope.onComplete(http.responseText);
			}
		}
	}
	http.send(params);
};



/**
 * ...
 * @author Hatshepsout
 */

function AppConstants(){}

AppConstants.BASE_SIZE = 660;



/**
 * ...
 * @author Hatshepsout
 */

function ImageResizer(){}


ImageResizer.MAX_IMAGE_WIDTH =  800;

ImageResizer.resize = function( img )
{
	var maxWidth = ImageResizer.MAX_IMAGE_WIDTH;
	var canvas = document.createElement("canvas");
	var context = canvas.getContext("2d");
	var ratio = ( img.width > maxWidth ) ? img.width / maxWidth : 1 ;
	var width = img.width / ratio;
	var height = img.height / ratio;
	var dataURL = "";
	
	canvas.width = width;
	canvas.height = height;
	
	context.save();
	context.scale( 1/ratio, 1/ratio );
	context.drawImage(img,0,0);
	context.restore();
	
	dataURL = canvas.toDataURL();
	return dataURL;
};



/**
 * ...
 * @author Hatshepsout
 */


function Localization()
{
	this._data = new Object();
	Localization._instance = this;
}

Localization.prototype._data = null;
Localization._instance = null;
Localization.getInstance = function()
{
	var instance = Localization._instance || new Localization();
	return instance;
};

Localization.prototype.addLabel = function(p_label, p_value, p_lang)
{
	p_lang = p_lang || "fr_FR";
	this._data[p_lang] = this._data[p_lang] || new Object();
	this._data[p_lang][p_label] = p_value;
};

Localization.prototype.getLabel = function(p_label, p_lang )
{
	p_lang = p_lang || "fr_FR";
	this._data[p_lang] = this._data[p_lang] || new Object();
	return this._data[p_lang][p_label] || p_label;
};





/**
 * ...
 * @author Hatshepsout
 */

function Mouse(){}

Mouse.RESIZE = "resizeCursor";
Mouse.DRAG = "moveCursor";
Mouse.KILL = "killCursor";
Mouse.ROTATE = "rotateCursor";
Mouse.DEFAULT = "defaultCursor";

Mouse.setCursor = function(value)
{
	tomahawk_ns.Stage.getInstance().getCanvas().setAttribute("class",value);
};

